import fs from 'fs';
import path from 'path';
import { Context } from '../../core';
import { copy } from '../../utils';

export async function generateFiles(context: Context) {
  // generate assets file
  await generateAssets(context);
  // generate chunk file
  await generateChunksFile(context);
}

async function generateAssets(context: Context) {
  await Promise.all(Object.entries(context.assets).map(([originPath, outputFileName]) => {
    copy(originPath, path.resolve(context.config.output.path, outputFileName));
  }));
}

async function generateChunksFile(context: Context) {
  const chunks = context.chunkGraph.getChunks();
  chunks.forEach(chunkId => {
    const chunk = context.chunkGraph.getChunk(chunkId);
    fs.writeFileSync(path.resolve(context.config.output.path, chunk.getFileName()), chunk.code);
  });
}
